<template>
  <!--引用表格-->
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <!--插槽:table标题-->
    <template #tableTitle>
      <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd">新增</a-button>
      <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
      <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
      <template v-if="selectedRowKeys.length > 0">
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="onUnlinkDepartUserBatch">
                <icon icon="bx:bx-unlink" />
                <span>取消关联</span>
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>
            <span>批量操作 </span>
            <icon icon="akar-icons:chevron-down" />
          </a-button>
        </a-dropdown>
      </template>
    </template>
    <!-- 插槽：行内操作按钮 -->
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" />
    </template>
  </BasicTable>
  <SignalModal @register="registerModal" :modelData="deviceModelList" @success="reload" />
</template>

<script lang="ts" setup>
  import { computed, inject, ref, unref, watch, reactive } from 'vue';
  import { ActionItem, BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import SignalModal from './SignalModal.vue';
  import { getDeviceModelByType, getDeviceModelById } from '../../deviceModel/deviceModel.api';
  import { list, deleteSignal, batchDeleteSignal, getExportUrl, getImportUrl } from '../signal.api';
  import { paramDeviceTypeId, columns, searchFormSchema } from '../signal.data';
  import { ColEx } from '/@/components/Form/src/types';
  import { truncate } from 'fs-extra';
  import { useUserStore } from '/@/store/modules/user';

  const userStore = useUserStore();
  const tenantId = userStore.getTenant;

  const prefixCls = inject('prefixCls');
  const props = defineProps({
    data: { require: true, type: Object },
  });
  // 当前选中的设备类型ID，可能会为空，代表未选择设备类型
  const deviceTypeId = computed(() => props.data?.id);
  const deviceModelList = reactive([]);

  // 自适应列配置
  const adaptiveColProps: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 24, // ≥576px
    md: 24, // ≥768px
    lg: 12, // ≥992px
    xl: 12, // ≥1200px
    xxl: 8, // ≥1600px
  };
  // 列表页面公共参数、方法
  const { tableContext, createMessage, onExportXls, onImportXls } = useListPage({
    tableProps: {
      api: list,
      columns: columns,
      canResize: false,
      formConfig: {
        schemas: searchFormSchema,
        baseColProps: adaptiveColProps,
        labelAlign: 'left',
        labelCol: {
          xs: 24,
          sm: 24,
          md: 24,
          lg: 9,
          xl: 7,
          xxl: 5,
        },
        wrapperCol: {},
        // 操作按钮配置-查询、重置
        actionColOptions: {
          xs: 24,
          sm: 6,
          md: 6,
          lg: 6,
          xl: 6,
          xxl: 6,
        },
        resetFunc: customResetFunc
      },
      actionColumn: {
        width: 160,
        title: '操作',
        dataIndex: 'action',
        fixed: 'right'
      },
      // 请求之前对参数做处理
      beforeFetch(params) {
        params.typeId = deviceTypeId.value;
      },
    },
    exportConfig: {
      name: '串口设备列表',
      url: getExportUrl,
    },
    importConfig: {
      url: getImportUrl,
    },
  });

  // 注册 ListTable
  const [registerTable, { getForm, reload, setProps, setLoading, updateTableDataRecord }, { rowSelection, selectedRowKeys }] = tableContext;

  watch(
    () => props.data,
    () => {
      paramDeviceTypeId.value = props.data.id;
      loadDeviceModelListByType(paramDeviceTypeId.value);
      reload()
    }
  );


  // 注册用户选择 modal
  const [registerModal, { openModal }] = useModal();

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '删除',
        color: 'error',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }

  /**
   * 根据设备型号类型获得设备型号数据集
   */
  async function loadDeviceModelListByType(typeId){
    const list = await getDeviceModelByType({typeId: typeId});
    deviceModelList.splice(0,deviceModelList.length)
    list.forEach(p => {
      deviceModelList.push({label: p.model, value: p.id});
    });
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      record: {
        typeId: deviceTypeId.value 
      },
      isUpdate: false,
    });
  }

  /**
   * 编辑事件
   */
  async function handleEdit(record) {
    if(deviceModelList.length==0){
      const deviceModel = await getDeviceModelById({ id: record.modelId });
      if(deviceModel){
        deviceModelList.push({label: deviceModel.model, value: deviceModel.id});
      }
    }
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteSignal({ id: record.id }, reload);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDeleteSignal({ ids: selectedRowKeys.value }, reload);
  }

  /**
   * 重置事件
   */
  async function customResetFunc(){
    props.data.id = '';
  }
</script>
